import { useEffect, useState } from "react";
import { View } from "@tarojs/components";
import {
  Layout,
  WithMargins,
  C06HeroSlideBanner,
  C07MainTitleArea,
  C09Address,
  C10TabSection,
  C12Recommendation,
  C13BottomDock,
  C38ExhibitionPickerGroup,
} from "@/components";
import { useAuth } from "@/store/authContext";
import useDetailPageData from "@/hooks/useDetailPageData";
import { ModalTypes, useApplicationInfo } from "@/store/applicationDataContext";
import { useUserInfo } from "@/store/userDataContext";
import {
  ApiAppointmenStatus,
  ExhibitionShape,
} from "@/data/exhibitions/exhibitionTypes";
import { ApiItemTypeMapping } from "@/data/shared/entityShapes";
import { apiItemTypeMapping } from "@/utils/apiMapping";
import { colors } from "@/data/shared/colors";
import { navigateTo, switchTab } from "@/utils/navigation";
import { BottomDockButtonShape } from "@/components/c13-BottomDock";
import { ActionKeys, ActionNames, sendAction } from "@/utils/tracking";
import { useEventListSplit } from "@/hooks/useEventListSplit";
import style from "./index.module.scss";
import Taro from "@tarojs/taro";

export default function ExhibitionDetail() {
  const { dispatchAuthAction } = useAuth();
  const { userInfoState } = useUserInfo();
  const { selectedEventData } = userInfoState;
  const { dispatch } = useApplicationInfo();
  const [exhibionData, liked, preview] = useDetailPageData("exhibition") as [
    ExhibitionShape,
    Boolean,
    Boolean
  ];

  const [price, setPrice] = useState(0);
  const isBookable = exhibionData?.cityName === "上海";

  // For exhibition to populate sharing
  useEffect(() => {
    if (exhibionData) {
      dispatch({
        type: "SET_SHARE_DATA",
        data: {
          text: exhibionData.name,
          imagePath: exhibionData.sharePoster
            ? exhibionData.sharePoster
            : exhibionData.cover,
        },
      });

      sendAction(ActionNames.ExhibitionDetailImpression, {
        [ActionKeys.ExhibitionName]: exhibionData.name,
        [ActionKeys.ExhibitionLocation]: exhibionData?.address.courseAddress,
      });
    }
  }, [exhibionData]);

  const trackPrimaryCtaClick = () => {
    sendAction(ActionNames.ExhibitionDetailWebLinkClick, {
      [ActionKeys.ExhibitionName]: exhibionData?.name,
      [ActionKeys.ExhibitionLocation]: exhibionData?.address.courseAddress,
      [ActionKeys.ExhibitionPrice]: exhibionData?.price + "",
      [ActionKeys.ExhibitionDate]: selectedEventData?.schedulingDate ?? "",
      [ActionKeys.ExhibitionTime]: selectedEventData?.schedulingStartTime ?? "",
      [ActionKeys.ExhibitionLanguage]: "",
    });
  };
  const eventRecSplit = useEventListSplit(exhibionData);

  const bookEvents = async () => {
    if (exhibionData && selectedEventData) {
      exhibionData.handlePlaceOrder({
        query: {
          type: ApiItemTypeMapping.Exhibition,
          preOrderDetail: {
            mainId: exhibionData.id,
            count: 1,
            scheduleLings: [
              {
                courseId: exhibionData.id,
                scheduleId: selectedEventData.schedulingId,
              },
            ],
          },
          preOrderType: "buyNow",
        },
      });

      trackPrimaryCtaClick();
    }
  };

  const lineUp = async () => {
    if (exhibionData) {
      const result = await exhibionData.handleLineUp({
        query: {
          mainId: exhibionData.id,
          type: ApiItemTypeMapping.Exhibition,
        },
        authDispatch: dispatchAuthAction,
      });
      if (result) {
        navigateTo(`pages/user-waiting-list/index`);
      }
      trackPrimaryCtaClick();
    }
  };

  const DEFAULT_PRIMARY_CTA_BOOK = {
    cb: bookEvents,
    text: "预约展览",
  };
  const DEFAULT_SECONDARY_CTA_NULL = null;

  const LINE_UP = {
    cb: lineUp,
    text: "候补登记",
  };
  const BOOK_AGAIN = {
    //1
    cb: bookEvents,
    text: "重新预约",
  };

  const SHOW_QR_CODE = {
    //1
    cb: () => {
      trackPrimaryCtaClick();
      dispatch({ type: "SHOW_MODAL", data: ModalTypes.QR });
    },
    text: "出示预约码",
  };

  const GO_TO_DISCOVER = {
    //2
    cb: () => {
      trackPrimaryCtaClick();
      switchTab("pages/discover/index");
    },
    text: "探索更多",
  };

  // 跳转视频号
  const GO_TO_CHANNELID = {
    //
    cb: () => {
      trackPrimaryCtaClick();

      // 跳转视频号
      Taro.openChannelsActivity({
        finderUserName: exhibionData.channelsId,
        feedId: exhibionData.videoId
      })

    },
    text: "探索更多",
  }

  const [primaryCta, setPrimaryCta] = useState<BottomDockButtonShape>(
    DEFAULT_PRIMARY_CTA_BOOK
  );
  const [secondaryCta, setSecondaryCta] =
    useState<BottomDockButtonShape | null>(DEFAULT_SECONDARY_CTA_NULL);

  useEffect(() => {
    if (exhibionData) {
      setPrimaryCta(DEFAULT_PRIMARY_CTA_BOOK);
      setSecondaryCta(DEFAULT_SECONDARY_CTA_NULL);

      if (!isBookable) {

        if (exhibionData.link) {
          setPrimaryCta({
            cb: () => {
              navigateTo(
                `pages/web-view-container/index?link=${exhibionData.link ?? ""
                }&name=${exhibionData.name}`
              );
            },
            text: "探索更多",
          });
        } else {
          setPrimaryCta(GO_TO_CHANNELID);
        }


      } else {
        if (exhibionData.isDeleted || !exhibionData.status) {
          if (exhibionData.channelsId) {
            setPrimaryCta(GO_TO_CHANNELID);
          } else {
            setPrimaryCta(GO_TO_DISCOVER);
          }
        } else {
          switch (exhibionData.appointmentStatus) {
            case ApiAppointmenStatus.InProgress:
              if (!exhibionData.totalSeatsLeftForAllScheduledExhibition) {
                if (exhibionData.orderQuantityToBeWrittenOff === 0) {
                  if (exhibionData.completedOrderQuantity! > 0) {
                    if (exhibionData.channelsId) {
                      setPrimaryCta(GO_TO_CHANNELID);
                    } else {
                      setPrimaryCta(GO_TO_DISCOVER);
                    }

                    setSecondaryCta(LINE_UP);
                  } else {
                    setPrimaryCta(LINE_UP);
                  }
                } else {
                  setPrimaryCta(SHOW_QR_CODE);
                  setSecondaryCta(LINE_UP);
                }
              } else {
                if (exhibionData.isAppointment) {
                  setSecondaryCta(BOOK_AGAIN);
                  setPrimaryCta(SHOW_QR_CODE);
                  if (exhibionData.completedOrderQuantity! > 0) {
                    if (exhibionData.orderQuantityToBeWrittenOff === 0) {
                      if (exhibionData.channelsId) {
                        setPrimaryCta(GO_TO_CHANNELID);
                      } else {
                        setPrimaryCta(GO_TO_DISCOVER);
                      }
                    }
                  }
                }
              }
              break;
            case ApiAppointmenStatus.NotStarted:
              // Disabled
              setPrimaryCta({
                //4
                cb: () => {
                },
                disabled: true,
                text: "即将开展",
              });
              break;
            case ApiAppointmenStatus.Ended:
              if (exhibionData.channelsId) {
                setPrimaryCta(GO_TO_CHANNELID);
              } else {
                setPrimaryCta(GO_TO_DISCOVER);
              }
              break;

            default:
              console.log("default");
              break;
          }
        }
      }
      setPrice(exhibionData.price);
      if (selectedEventData) {
        setPrice(selectedEventData.price || 0);
      }
    }
  }, [exhibionData, selectedEventData]);

  return (
    <Layout>
      <View className={style.wrapper}>
        {exhibionData && (
          <>
            {!!exhibionData.carouselMap.length && (
              <C06HeroSlideBanner
                images={exhibionData.carouselMap}
                videoSrc={
                  exhibionData.mainPictureVideo
                    ? exhibionData.mainPictureVideo
                    : null
                }
                themeColor={colors.colorExhibition}
              />
            )}

            <WithMargins>
              <C07MainTitleArea
                themeColor={colors.colorExhibition}
                heading={exhibionData.name}
                dateRange={{
                  start: exhibionData.startTime,
                  end: exhibionData.endTime,
                }}
                price={price}
              />

              {/* TODO: as ongoing API updates, this list may need to filter out if not done in backend:
                  1. Unavailalbe time-slots
                  2. Finished events
              */}
              {isBookable && !!exhibionData.schedulingList?.length && (
                <C38ExhibitionPickerGroup
                  eventData={exhibionData.schedulingList.flatMap(
                    (exhibitionDateObj) =>
                      exhibitionDateObj.timeSlots.flatMap((timeSlotObj) => ({
                        schedulingId: timeSlotObj.sechdulingId,
                        schedulingDate: exhibitionDateObj.date,
                        schedulingStartTime: timeSlotObj.timeStart,
                        schedulingEndTime: timeSlotObj.timeEnd,
                        remainingSeatCount: timeSlotObj.remainingSeatCount,
                        price: timeSlotObj.price,
                      }))
                  )}
                />
              )}

              {/* Variations for exhibitions in Shanghai and other locations */}
              {isBookable ? (
                <C09Address
                  upperLine={exhibionData.address.courseAddress}
                  lowerLine={exhibionData.address.courseAddressInfo}
                  lat={+exhibionData.address.lat}
                  lon={+exhibionData.address.lon}
                  dest={exhibionData.address.dest}
                />
              ) : (
                <C09Address upperLine={exhibionData.cityName} />
              )}
            </WithMargins>

            {/* Tabbed view */}
            <C10TabSection tabContent={exhibionData.exhibitionInfo.details} />

            {/* Recommended-events-slider */}
            {!!eventRecSplit.courses.length && (
              <C12Recommendation
                recommendationTitle="课程推荐"
                // Remap to not have changing types restrict too much
                cardData={eventRecSplit.courses.map((relatedEvent) => ({
                  cardId: relatedEvent.aboutId,
                  imagePath: relatedEvent.sharePoster || relatedEvent.cover,
                  title: relatedEvent.name,
                  tag: relatedEvent.typeName,
                  cost: relatedEvent.price,
                  type: "course-card",
                  themeColor: relatedEvent.labelColor,
                  redirect: apiItemTypeMapping[relatedEvent.typeCourse],
                }))}
              />
            )}
            {(!!exhibionData.shopRecommendations?.length ||
              !!eventRecSplit.otherEvents.length) && (
                <C12Recommendation
                  recommendationTitle="您也可能喜欢"
                  type="mixed"
                  cardData={[
                    ...(exhibionData.shopRecommendations ?? []),
                    ...eventRecSplit.otherEvents,
                  ].map((recommendItem) => ({
                    cardId: recommendItem.aboutId,
                    imagePath: recommendItem.sharePoster || recommendItem.cover,
                    title: recommendItem.name,
                    cost: recommendItem.price,
                    type: "recommendation-mixed",
                    themeColor: recommendItem.labelColor,
                    redirect: apiItemTypeMapping[recommendItem.typeCourse],
                  }))}
                />
              )}
          </>
        )}
      </View>

      {exhibionData && !preview && (
        <C13BottomDock
          onPrimaryClick={primaryCta}
          onSecondaryClick={secondaryCta}
          onSaveClick={() => {
            exhibionData.handleFav(
              exhibionData!.id,
              ApiItemTypeMapping.Exhibition
            );
          }}
          liked={liked ? true : false}
        />
      )}
    </Layout>
  );
}
